/*
 * fun [function] 需要防抖的函数
 * delay [number] 毫秒，防抖期限值
 */
function debounce(fun, delay = 300) {
  let timer;
  return function () {
    let ctx = this
    let args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      timer = null
      fun.apply(ctx, args)
    }, delay)
  }
}
/*
 * fun [function] 需要节流的函数
 * delay [number] 毫秒，节流期限值
 */
function throttle(fun, interval = 300) {
  let last;
  let timer;
  return function () {
    let ctx = this
    let args = arguments
    let now = new Date()
    if (last && now - last < interval) {
      clearTimeout(timer)
      timer = setTimeout(function () {
        last = now
        fun.apply(ctx, args)
      }, interval)
    } else {
      last = now
      fun.apply(ctx, args)
    }
  }
}

// 时间排序功能    点击升序降序
function isSort(type, arr) {
  if (type) {
    arr.sort((x, y) => {
      return Date.parse(x.update) - Date.parse(y.update)
    })
  } else {
    arr.sort((x, y) => {
      return Date.parse(y.update) - Date.parse(x.update)
    })
  }
}

const app = getApp()
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');

function _getPosition(){  //  获取定位信息
  let qqmap = new QQMapWX({
    key: "D4VBZ-75U6F-7DNJJ-J3TK6-MRVHZ-XFBN4"
  })
  return new Promise((resolve,reject)=>{
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: result => {
        qqmap.reverseGeocoder({
          location: {
            latitude: result.latitude,
            longitude: result.longitude
          },
          success: res => {
            resolve(res)
          },
          fail: err =>{
            reject(err)
          }
        })
      }
    })
  })
}

function handletabChange(data) {
  switch(data){
    case 0:
      wx.reLaunch({
        url: '/driver_side/pages/order-hall/index/index'
      });
      break;
    case 1:
      wx.reLaunch({
        url: '/driver_side/pages/process/index/index'
      });
      break;
    case 2:
      wx.reLaunch({
        url: '/driver_side/pages/achievement/index/index'
      });
      break;
    case 3:
      wx.reLaunch({
        url: '/driver_side/pages/mine/index/index'
      });
      break;
  }
}
/**
 * @desc 防抖函数
 * @param {需要防抖的函数} func
 * @param {延迟时间} wait
 * @param {是否立即执行} immediate
 */
function debounces(func, wait, immediate) {
  let timeout
  return function(...args) {
    let context = this
    if (timeout) clearTimeout(timeout)
    if (immediate) {
      let callNow = !timeout
      timeout = setTimeout(function() {
        timeout = null
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timeout = setTimeout(function() {
        func.apply(context, args)
      }, wait)
    }
  }
}
export {
  debounce,
  throttle,
  isSort,
  _getPosition,
  handletabChange,
  debounces
}